﻿using AutoMapper;
using B.S.BasicData.Domain;
using B.S.BasicData.ErrorCode;
using B.S.BasicData.Infrastructure.Interfance;
using B.S.BasicData.Write.Application.Common.User;
using MediatR;
using System.Transactions;

namespace B.S.BasicData.Write.Application.Handler.User
{
    public class DelUserHandler : IRequestHandler<DelUserCommon, ApiResult<int>>
    {
        private readonly IBaseRepository<UserModel> userRepo;
        private readonly IMapper mapper;

        public DelUserHandler(IBaseRepository<UserModel> userRepo,IMapper mapper)
        {
            this.userRepo = userRepo;
            this.mapper = mapper;
        }
        public Task<ApiResult<int>> Handle(DelUserCommon request, CancellationToken cancellationToken)
        {
            ApiResult<int> res=new ApiResult<int>();

            //var username = userRepo.GetAll().Where(x => x.UserName == request.UserName).FirstOrDefault();
            //if (username != null)
            //{
            //    res.Code=ApiEnum.Error;
            //    res.Message = "用户名已存在";
            //    return Task.FromResult(res);
            //}
            var user = userRepo.GetValue(request.UserId).Result;
            user.IsDel = true;
            var r = 0;
            using (TransactionScope tran=new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            {
                r = userRepo.Update(user).Result;
                tran.Complete();
            }

            if(r>0)
            {
                res.Code = ApiEnum.Success;
                res.Message = "删除成功";
                return Task.FromResult(res);
            }
            else
            {
                res.Code = ApiEnum.Error;
                res.Message = "删除失败";
                return Task.FromResult(res);
            }


        }
    }
}
